document.addEventListener('DOMContentLoaded', function () {
    var form = document.getElementById('chat-form');
    var messagesDiv = document.getElementById('chat-messages');
    var submitButton = form.querySelector('button[type="submit"]');
    
    // 当表单提交时触发
    form.addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        var userInput = document.getElementById('user-input').value;
        if (userInput.trim() === '') return; // 如果输入为空，则不发送

        // 锁定提交按钮，防止连续发送
        submitButton.disabled = true;

        // 将用户消息添加到聊天记录中，使用消息气泡样式
        var userMessageBubble = createMessageBubble('user', userInput);
        messagesDiv.appendChild(userMessageBubble);

        // 使用fetch API发送请求到后端
        fetch('/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ message: userInput })
        })
        .then(response => response.json())
        .then(data => {
            // 将回复添加到聊天记录中，使用消息气泡样式
            var botResponseBubble = createMessageBubble('bot', data.response);
            messagesDiv.appendChild(botResponseBubble);

            // 清空输入框
            document.getElementById('user-input').value = '';

            // 解锁提交按钮
            submitButton.disabled = false;

            // 滚动到底部
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        })
        .catch(error => {
            console.error('Error:', error);
            // 解锁提交按钮，在出错情况下
            submitButton.disabled = false;
        });
    });

    // 创建消息气泡的函数
    function createMessageBubble(sender, text) {
    var bubble = document.createElement('div');
    bubble.className = `message-bubble ${sender}`;
    bubble.innerHTML = `
        <p>${text}</p>
        <small class="time-stamp">${new Date().toLocaleTimeString()}</small>
    `;
    return bubble;
}
});

document.addEventListener('DOMContentLoaded', function() {
    // 获取聊天记录并显示
    async function fetchChatHistory(user_id) {
        try {
            const response = await fetch(`/get_chat_history/${user_id}`);
            const data = await response.json();
            displayChatHistory(data);
        } catch (error) {
            console.error('Error fetching chat history:', error);
        }
    }

    // 显示聊天记录
    function displayChatHistory(data) {
        const chatMessagesDiv = document.getElementById('chat-messages');
        chatMessagesDiv.innerHTML = ''; // 清空现有消息
        data.forEach(record => {
            const userMessageDiv = document.createElement('div');
            userMessageDiv.textContent = `User: ${record.user_input}`;
            const modelResponseDiv = document.createElement('div');
            modelResponseDiv.textContent = `Model: ${record.model_response}`;
            chatMessagesDiv.appendChild(userMessageDiv);
            chatMessagesDiv.appendChild(modelResponseDiv);
        });
    }

    // 监听聊天列表中的按钮点击事件
    const chatItems = document.querySelectorAll('.chat-item');
    chatItems.forEach(item => {
        item.addEventListener('click', function() {
            const userId = 1; // 假设用户 ID 为 1
            fetchChatHistory(userId);
        });
    });

    // 发送消息
    const chatForm = document.getElementById('chat-form');
    chatForm.addEventListener('submit', async function(event) {
        event.preventDefault();
        const userInput = document.getElementById('user-input').value.trim();
        if (userInput !== '') {
            try {
                // 发送消息到后端
                const response = await fetch('/send_message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message: userInput, user_id: 1 }) // 假设用户 ID 为 1
                });
                const result = await response.json();
                if (result.status === 'success') {
                    document.getElementById('user-input').value = '';
                    // 重新获取聊天记录
                    fetchChatHistory(1); // 假设用户 ID 为 1
                }
            } catch (error) {
                console.error('Error sending message:', error);
            }
        }
    });
});